import type { ReactNode } from "react";
import React, { useRef, useState } from "react";
import type { ActionType, ProColumns } from "@ant-design/pro-table";
import ProTable from "@ant-design/pro-table";
import { Button, Divider, Modal } from "antd";
import { PageContainer } from "@ant-design/pro-layout";
import { request } from "@@/plugin-request/request";
import { EllipsisOutlined, ExclamationCircleOutlined } from "@ant-design/icons/lib";
import { AliyunOSSUpload } from "@/oss";
import qr from "qr-image";
import "./GuestList.css"

const { confirm } = Modal;

async function query(params?: Record<string, unknown>) {
  return request(`${process.env.hostname}/api/guest/list`, {
    params,
  });
}

async function save(params: any) {
  return request(`${process.env.hostname}/api/guest/save`, {
    method: 'post',
    data: params,
    requestType: 'form'
  });
}

function remove(id: number, actionRef: any) {
  confirm({
    title: '确定删除?',
    icon: <ExclamationCircleOutlined />,
    okText: '确定',
    cancelText: '取消',
    onOk() {
      return request(`${process.env.hostname}/api/guest/delete`, {
        method: 'post',
        params: { 'id': id }
      }).then(result => {
        if (result.success) {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      })
    }
  });
}

const TableList: React.FC = () => {
  const [modalVisible, handleModalVisible] = useState(false);
  const [formValues, setFormValues] = useState({});
  const [title, setTitle] = useState('')
  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      title: 'Id',
      dataIndex: 'id',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '客户名称',
      dataIndex: 'name',
    },
    {
      title: '照片（限制50张）',
      dataIndex: 'photos',
      hideInSearch: true,
      renderFormItem: (_, { type }) => {
        if (type !== 'form') {
          return null
        }
        return <AliyunOSSUpload multiple fileType={'img'}/>

      },
      // fieldProps: 'value'
      render: (value: ReactNode) => {
        const arr = value as string[];

        return <div style={{ display: "inline-flex", width: '350px', flexWrap: 'wrap' }}>
          {arr.slice(0, 3).map((it, i) =>
            <div key={i} className='img-box'>
              <img src={it} alt="logo" className='photo-img' />
            </div>)
          }
          {arr.length > 3 && <EllipsisOutlined />}
        </div>
        // return value && (value as []).startsWith("http") ?
        //   <img src={value.toString()} alt="logo" style={{ maxHeight: '100px' }} /> : "-"
      }
    },
    {
      title: '动感MV',
      tooltip: '视频转码预计1-2min，上传完成后请稍等片刻播放',
      dataIndex: 'videoUrl',
      hideInSearch: true,
      renderFormItem: (_, { type }) => {
        if (type !== 'form') {
          return null
        }
        return <AliyunOSSUpload fileType={'video'}/>
      },
      render: (value) => {
        const url = value as string
        return url && url.startsWith("http") ? (<a href={url} target="_blank">{url}</a>) : "-"
      }
    },
    {
      title: '分享二维码',
      hideInSearch: true,
      render: (_, dom) => {
        const q2 = qr.imageSync(`http://share.lanjing.cc/share/${dom.id}`, { type: 'png', size: 20 })
        const a = URL.createObjectURL(
          new Blob([q2.buffer], { type: 'image/png' } /* (1) */)
        );
        return <img src={a} alt="qr" style={{ width: '100px' }} />
      }
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        const q2 = qr.imageSync(`http://share.lanjing.cc/share/${record.id}`, { type: 'png', size: 20 })
        const a = URL.createObjectURL(
          new Blob([q2.buffer], { type: 'image/png' } /* (1) */)
        );
        return (
          <>
            <a onClick={() => {
              handleModalVisible(true);
              setFormValues(record);
              setTitle('修改')
            }}>修改</a>
            <Divider type="vertical" />
            <a onClick={() => remove(record.id, actionRef)}>删除</a>
            <Divider type="vertical" />
            <a href={a} download={`二维码-${record.name}.png`}>下载二维码</a>
          </>
        )
      },
    },
  ];

  return <PageContainer>
    <ProTable
      actionRef={actionRef}
      search={{ filterType: 'query' }}
      rowKey="id"
      toolBarRender={() => [
        <Button type="primary" onClick={() => {
          handleModalVisible(true)
          setFormValues({});
          setTitle('新建')
        }}>
          新建
        </Button>,
      ]}
      request={(params, sorter) => query({ ...params, sorter })}
      columns={columns}
    />

    <Modal width={480} visible={modalVisible} title={title}
           onCancel={() => handleModalVisible(false)} footer={null}
           destroyOnClose
    >
      <ProTable type="form"
                columns={columns}
                rowKey="id"
                form={{ initialValues: formValues, submitter: { searchConfig: { resetText: '撤销修改' } } }}
                onSubmit={async (value: any) => {
                  const result = await save({ ...formValues, ...{ videoUrl: null }, ...value });

                  if (result.success) {
                    handleModalVisible(false);
                    if (actionRef.current) {
                      actionRef.current.reload();
                    }
                  }
                }}
      />
    </Modal>

  </PageContainer>;
};

export default TableList;
